#include "tcpclient.h"
#include <QDebug>
TcpClient::TcpClient(QObject *parent)
    : QObject{parent}
    ,m_tcpSocket(new QTcpSocket(this))
{
    qDebug()<<QString("int %1:%2").arg(ip).arg(port);
    connect(m_tcpSocket, &QTcpSocket::connected, this, &TcpClient::onSocketConnected);
    connect(m_tcpSocket, &QTcpSocket::disconnected, this, &TcpClient::onSocketDisconnected);
    connect(m_tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::onSocketReadyRead);
    connect(m_tcpSocket, &QTcpSocket::errorOccurred, this, &TcpClient::onSocketErrorOccurred);
    connect(&timer,&QTimer::timeout,this,[=](){
        if(!m_tcpSocket->isOpen()){
            qDebug()<<QString("try %1:%2").arg(ip).arg(port);
            m_tcpSocket->connectToHost(ip,port);
        }
    });
    timer.start(1000);
}

void TcpClient::write(QByteArray &d)
{
    if(m_tcpSocket->isOpen()){
        m_tcpSocket->write(d);
    }
}

void TcpClient::onSocketConnected()
{
    qDebug()<<QString("connected %1:%2").arg(ip).arg(port);
}

void TcpClient::onSocketDisconnected()
{
    qDebug()<<QString("disconnected %1:%2").arg(ip).arg(port);
}

void TcpClient::onSocketErrorOccurred(QAbstractSocket::SocketError error)
{
 qDebug()<<QString("error %1:%2: ").arg(ip).arg(port)<<error;
}

void TcpClient::onSocketReadyRead()
{
    qDebug()<<QString("read %1:%2: ").arg(ip).arg(port)<<m_tcpSocket->readAll();
}
